/**
 * 
 */
package com.alstudio.ui.module.user;

import java.io.File;
import java.util.ArrayList;

import wxapi.WeiXinShareDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ViewFlipper;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.app.VersionConfig;
import com.alstudio.core.voip.ALVoipCallManager;
import com.alstudio.core.voip.CallState;
import com.alstudio.module.sns.weiboshare.ShareContentParam;
import com.alstudio.module.sns.weiboshare.WeiboShareUtil;
import com.alstudio.module.sns.weiboshare.WeiboShareUtil.SaveImageCallback;
import com.alstudio.module.sns.weiboshare.WeiboShareUtil.WeiboShareMenuItem;
import com.alstudio.module.voip.ALVoipEvent;
import com.alstudio.module.xmpp.protocol.xmpp.XmppErrorCode;
import com.alstudio.module.xmpp.protocol.xmpp.data.ALPhoto;
import com.alstudio.module.xmpp.protocol.xmpp.packact.ALMessage;
import com.alstudio.module.xmpp.request.ALUiXmppRequestCreator;
import com.alstudio.pojo.ALXmppEvent;
import com.alstudio.pojo.module.server.Serverlet;
import com.alstudio.pojo.module.user.User;
import com.alstudio.pojo.module.user.Voiceintro;
import com.alstudio.ui.base.TitleBarActivity;
import com.alstudio.ui.module.image.browser.ImageDetailFragment;
import com.alstudio.ui.module.image.browser.LargerPhotoActivity;
import com.alstudio.ui.module.voip.CallActivity;
import com.alstudio.utils.android.ALFileManager;
import com.alstudio.utils.android.ALSdcardManager;
import com.alstudio.utils.android.device.ALDisplayMetricsManager;
import com.alstudio.utils.android.media.audio.player.ALAudioPlayTask;
import com.alstudio.utils.android.media.audio.player.ALAudioPlayTask.ALAudioPlayTaskCallback;
import com.alstudio.utils.android.media.audio.recorder.ALAudioRecordManager;
import com.alstudio.utils.android.media.audio.recorder.ALAudioRecordTask;
import com.alstudio.utils.android.media.audio.recorder.ALAudioRecordTask.ALAudioRecordTaskCallback;
import com.alstudio.utils.android.media.audio.recorder2.ALAudioRecordTask2;
import com.alstudio.utils.android.net.download.ALHttpDownloadTask.ALHttpDownloadErrorCode;
import com.alstudio.utils.android.net.http.UploadPhotoRequest;
import com.alstudio.utils.android.net.http.http2.UploadMediaRequest;
import com.alstudio.utils.android.net.http.http2.UploadMediaRequest.MediaUploadCallback;
import com.alstudio.utils.android.net.uploader.ALHttpUploadTaskManager;
import com.alstudio.utils.formater.FileIdUtils;
import com.alstudio.utils.image.ScreenCaptureUtil;
import com.alstudio.utils.log.ALLog;
import com.alstudio.utils.user.UserIconsUtil;
import com.alstudio.view.ViewUtils;
import com.alstudio.view.dialog.AlertDialogCreator;
import com.alstudio.view.listener.AlDialogOnClickListener;
import com.alstudio.view.listener.AlItemOnClickListener;
import com.alstudio.view.toast.MyToastUtil;
import com.loovee.imaohu.R;

/**
 * 用户主页
 * 
 * @author alonso lee
 * 
 */
public class UserHomePageAcitivty extends TitleBarActivity implements
		MediaUploadCallback, ALAudioRecordTaskCallback, OnPageChangeListener,
		ALAudioPlayTaskCallback {

	private User user;

	private RelativeLayout layout_top;
	// 小頭像
	private ImageView user_icon;

	private ArrayList<ALPhoto> photos;

	// 显示大图
	// private ImagePagerAdapter adapter;

	private LinearLayout photos_layout;

	private LinearLayout img_layout;

	private FrameLayout layout_middle;

	private final int SMALL_PHOTO_COUNT = 5;

	private boolean isMyHomePage = false;

	private ALAudioRecordTask voiceIntroRecordTask;

	private int audioLen = 0;

	private boolean isUserPlayFavoritesAction = false;

	// 播放对方大图头像
	private ViewFlipper flipper;

	// 关注按钮图标
	private View favorites_icon;
	// 电话按钮图标
	private View call_icon;
	// 右边按钮
	private ImageButton btn_opt;

	// 底部打电话布局
	private View call_layout;

	// // 判断是否需要留言
	// private boolean leaveAudioMsgRequest = false;
	// // 判断是否是提醒来电
	// private boolean callNoticeRequest = false;

	private final int MAKE_CALL_REQUEST = 0;
	private final int LEAVE_AUDIO_MSG_REQUEST = 1;
	private final int CALL_NOTICE_REQUEST = 2;
	private int makeCallState = MAKE_CALL_REQUEST;

	// 录制语音留言
	private ALAudioRecordTask2 audioRecorder;

	// 当前大图位置
	private int curViewPagerIndex = 0;

	// 判断当前是否正在循环播放图片
	private boolean isPlayingPic = false;

	// 判断用户是否取消了循环播放图片
	private boolean isUserCancelPlayPic = false;
	// 播放语音签名
	private ALAudioPlayTask mAudioPlayTask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		initData();
		setupView(this, getClass().getSimpleName());
	}

	@Override
	protected void setupView(Context context, String name) {
		// TODO Auto-generated method stub
		super.setupView(context, name);
		setTitleBarContentView(R.layout.user_home_page_layout);
		hideTitleBar();

		btn_opt = (ImageButton) findViewById(R.id.btn_opt);
		layout_top = (RelativeLayout) findViewById(R.id.layout_top);
		user_icon = (ImageView) findViewById(R.id.user_icon);
		photos_layout = (LinearLayout) findViewById(R.id.photos_layout);
		img_layout = (LinearLayout) findViewById(R.id.img_layout);
		layout_middle = (FrameLayout) findViewById(R.id.layout_middle);

		favorites_icon = findViewById(R.id.favorites_icon);
		call_icon = findViewById(R.id.call_icon);
		call_layout = findViewById(R.id.call_layout);
		flipper = (ViewFlipper) findViewById(R.id.flipper);

		setupLayoutParam();
		setViewOnclickListener(R.id.btn_back, this);
		setViewOnclickListener(R.id.btn_opt, this);
		setViewOnclickListener(R.id.nick_layout, this);
		setViewOnclickListener(R.id.record_btn, this);
		setViewOnclickListener(R.id.play_pic, this);
		setViewOnclickListener(R.id.photo_title, this);
		setViewOnclickListener(R.id.mute, this);
		setViewOnclickListener(R.id.call_layout, this);
		setViewOnclickListener(R.id.favorites_layout, this);
		setViewOnclickListener(R.id.goto_photos, this);

		initPhotoScrollViewPager();
		initViewFlipper();

		initAudioPlayer();

		if (!isMyHomePage) {
			// 查看他人主頁,隱藏錄音圖標
			goneView(R.id.record_btn);
			// 初始化语音留言
			initAudioMsgRecorder();

		} else {
			// 隐藏迪兰
			goneView(R.id.fun_layout);
			btn_opt.setImageResource(R.drawable.personal_icon_share);
			setViewOnclickListener(R.id.edit_nick_layout, this);
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#initData()
	 */
	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		user = (User) getIntent().getSerializableExtra("user");
		if (user == null) {
			user = ALLocalEnv.getLocalEnv().getMyProfile();
		}

		if (ALLocalEnv.getBareJid(user.getJid()).equals(
				ALLocalEnv.getLocalEnv().getMyAccount().getUserName())) {
			ALLog.d("查看自己的主頁");
			user = ALLocalEnv.getLocalEnv().getMyProfile();

			isMyHomePage = true;
			voiceIntroRecordTask = new ALAudioRecordTask(this, this);
			voiceIntroRecordTask.setMediaUploadCallback(this);
			voiceIntroRecordTask.setAutoProccess(false);
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#onPause()
	 */
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		stopPlayVoiceSig();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.BaseActivity#handleGetUserProfileEvent(com.alstudio
	 * .pojo.ALXmppEvent)
	 */
	@Override
	public void handleGetUserProfileEvent(ALXmppEvent data) {
		// TODO Auto-generated method stub
		super.handleGetUserProfileEvent(data);
		dismissLoadingProgress();
		if (data.getResponseCode() == ALXmppEvent.RESPONSE_OK) {
			User tmp = (User) data.getData();
			if (ALLocalEnv.getLocalEnv().isTheSameUser(tmp, user)) {
				isDataReceived = true;
				user = tmp;
				initPhotoScrollViewPager();
				initViewFlipper();
				stopViewPagerTask();
				startViewPagerTask();
				startViewPagerTask();
				setupUserInfo();
				setupBottomPhotos();
				// 开始播放语音了
				setAudioPlayerFileid();
				playVoiceSig();
				if (!isMyHomePage) {

					new Thread() {
						public void run() {
							// 更新數據庫中的黑名單和通話記錄
							ALLocalEnv.getLocalEnv().getDatabase()
									.updateBlackUserInfo(user);
							ALLocalEnv.getLocalEnv().getDatabase()
									.updateCallHitoryUserProfile(user);
						};
					}.start();
				}
			} else {
				ALLog.d("不是本次获取的用户资料");
			}
		} else {
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.BaseActivity#handleAddUserFavoritesEvent(com.alstudio
	 * .pojo.ALXmppEvent)
	 */
	@Override
	public void handleAddUserFavoritesEvent(ALXmppEvent data) {
		// TODO Auto-generated method stub
		super.handleAddUserFavoritesEvent(data);
		if (data.getResponseCode() == ALXmppEvent.RESPONSE_OK) {
			User tmp = (User) data.getData();
			if (!ALLocalEnv.getLocalEnv().isTheSameUser(tmp, user)) {
				ALLog.d("不是同一个用户对象，不管了");
				return;
			}
			if (data.getIntData() == 0) {
				// 普通收藏
				user.setFavorite(true);
				if (tmp.getIsfriend()) {
					user.setIsfriend("1");
				} else {
					user.setIsfriend("0");
				}
				// 更新底栏
				updateFunFavoriteState();
				updateFunCallState();
				int txt = R.string.TxtFavoritesSuccess;
				if (user.getIsfriend()) {
					txt = R.string.TxtSpecialFavoritesSuccess;
					// 更新数据库
					ALVoipCallManager.getDefaultALVoipManager()
							.updateCallUserFriendShipState(user.getJid(),
									user.getIsfriend());
				}
				if (isUserPlayFavoritesAction) {
					isUserPlayFavoritesAction = false;
					// 打出提示
					MyToastUtil.getInstance().showCenterToastOnCenter(txt);
				}
			} else {
				showFavoriteErrorToast(data.getResponseCode());
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.BaseActivity#handleDeleteFriendsOrFans(com.alstudio
	 * .pojo.ALXmppEvent)
	 */
	@Override
	public void handleDeleteFriendsOrFans(ALXmppEvent data) {
		// TODO Auto-generated method stub
		super.handleDeleteFriendsOrFans(data);
		if (data.getResponseCode() == ALXmppEvent.RESPONSE_OK) {
			User tmp = (User) data.getData();
			if (!ALLocalEnv.getLocalEnv().isTheSameUser(tmp, user)) {
				ALLog.d("不是同一个用户对象，不管了");
				return;
			}
			if (data.getIntData() == 0) {
				// 普通收藏
				user.setFavorite(false);
				user.setIsfriend("0");
				// 更新底栏
				updateFunFavoriteState();
				updateFunCallState();
				ALVoipCallManager.getDefaultALVoipManager()
						.updateCallUserFriendShipState(user.getJid(),
								user.getIsfriend());
				if (isUserPlayFavoritesAction) {
					isUserPlayFavoritesAction = false;
					// 打出提示
					MyToastUtil.getInstance().showCenterToastOnCenter(
							R.string.TxtDeleteFavoritesSuccess);
				}
			} else if (data.getIntData() == 1) {
				// 移除粉丝
				user.setFans(false);
				MyToastUtil.getInstance().showCenterToastOnCenter(
						R.string.TxtDeleteFans);
			}
		}
	}

	@Override
	public void handleMakeCallEvent(ALXmppEvent data) {
		// TODO Auto-generated method stub
		super.handleMakeCallEvent(data);
		if (data.getResponseCode() == 0) {
			Intent i = new Intent(this, CallActivity.class);
			data.getMessage().setData(user);
			i.putExtra("msg", data.getMessage());
			// i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
			// Intent.FLAG_ACTIVITY_SINGLE_TOP);

			startActivity(i);

			ALVoipCallManager.getDefaultALVoipManager().onCallStateChanged(
					CallState.CALL_OUTGOING, data.getMessage());

		} else {
			showMakeCallErrorToast(data.getResponseCode());
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#requeqtData()
	 */
	@Override
	public void requeqtData() {
		// TODO Auto-generated method stub
		super.requeqtData();
		if (ALLocalEnv.isSendXmppDataEnable() && !isDataReceived) {
			showLoadingProgress();
			if (user != null) {
				ALUiXmppRequestCreator.postALUIXmppGetUserProfileEvent(user
						.getJid());
			}
		}
	}

	/**
	 * 强制更新个人资料
	 */
	private void manualRequsetData() {
		if (ALLocalEnv.isSendXmppDataEnable()) {
			showLoadingProgress();
			if (user != null) {
				ALUiXmppRequestCreator.postALUIXmppGetUserProfileEvent(user
						.getJid());
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		setupUserInfo();
		requeqtData();
		startViewPagerTask();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		stopViewPagerTask();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.TitleBarActivity#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		super.onClick(v);
		if (!isDataReceived && v.getId() != R.id.btn_back && !isMyHomePage)
			return;
		switch (v.getId()) {
		case R.id.btn_back:
			finish();
			break;
		case R.id.btn_opt:
			// 彈出對話框
			invokeOptBtnClick();
			break;
		case R.id.record_btn:
			// 錄音
			voiceIntroRecordTask
					.showRecordWindow(findViewById(R.id.content_layout));
			break;
		case R.id.play_pic:
			// 播放、暫停圖片
			invokePlayViewPage();
			break;
		case R.id.mute:
			// 靜音
			invokePlayAudioSig();
			break;
		case R.id.edit_nick_layout:
			// 点击编辑签名
			invokeEditSig();
			break;
		case R.id.nick_layout:
			// 查看详情
			invokeViewUserDetail();
			break;
		case R.id.img_layout:
			// 查看圖片
			break;
		case R.id.layout_top:
			// 上传图片
			invokeUploadPicBtnClick();
			break;
		case R.id.photo_title:
		case R.id.goto_photos:
			gotoPhotoActivity();
			break;
		case R.id.favorites_layout:
			invokeFavoriteBtnClick();
			break;
		case R.id.call_layout:
			// makeCall();
			invokeCallLayoutClickEvent();
			break;
		case R.id.qzone:
			shareType = WeiboShareUtil.SHARE_TO_TENCENT;
			saveShareMagicPic();
			break;
		case R.id.weibo:
			shareType = WeiboShareUtil.SHARE_TO_SINA;
			saveShareMagicPic();
			break;
		case R.id.weixin:
			shareType = WeiboShareUtil.SHARE_TO_WEIXIN_2;
			saveShareMagicPic();
			break;
		case R.id.weixin_friend:
			shareType = WeiboShareUtil.SHARE_TO_WEIXIN_FRIEND;
			saveShareMagicPic();
			break;

		default:
			break;
		}
	}

	private void gotoPhotoActivity() {
		Intent intent = new Intent(this, PhotoActivity.class);
		intent.putExtra("user", user);
		startActivity(intent);
	}

	private void gotoLargerPhotoActivity(int i) {
		Intent intent = new Intent(this, LargerPhotoActivity.class);
		intent.putExtra("index", i);
		intent.putExtra("photos", user.getPhotos());
		intent.putExtra("isMyIcon", isMyHomePage);
		if (isMyHomePage) {
			intent.putExtra("vPos", ALLocalEnv.getLocalEnv().getMyProfile()
					.getvAuthPos());
		} else {
			intent.putExtra("vPos", user.getvAuthPos());
		}
		startActivity(intent);
	}

	/**
	 * 执行拨打电话
	 */
	private void invokeCallLayoutClickEvent() {

		if (makeCallState == MAKE_CALL_REQUEST) {

			switch (ALVoipCallManager.getDefaultALVoipManager()
					.getCurrentState()) {
			case CALL_DISCONNECT:
				break;
			case CALL_ESTABLISED:
				checkCallingUser();
				return;
			case CALL_HANDUP:
				break;
			case CALL_INCOMMING:
				ALVoipCallManager.getDefaultALVoipManager().rejectCall();
				break;
			case CALL_OUTGOING:
				ALVoipCallManager.getDefaultALVoipManager().handupCall();
				break;
			case CALL_REJECT:
				break;
			default:
				break;
			}

		}

		switch (makeCallState) {
		case MAKE_CALL_REQUEST:
			makeCall();
			break;
		case LEAVE_AUDIO_MSG_REQUEST:
			break;
		case CALL_NOTICE_REQUEST:
			break;
		}
	}

	private void checkCallingUser() {
		ALMessage msg = ALVoipCallManager.getDefaultALVoipManager()
				.getCallSession();
		User u = (User) msg.getData();
		if (ALLocalEnv.getLocalEnv().isTheSameUser(u, user)) {
			// 同一个用户，跳转到通话界面
			Intent i = new Intent(this, CallActivity.class);
			startActivity(i);
		} else {
			showReplaceCallNoticeDialog();
		}
	}

	private void showReplaceCallNoticeDialog() {
		AlertDialogCreator dialog = AlertDialogCreator
				.createTwoButtonNormalDialog(getApplicationContext(), false);
		dialog.setMessage(getString(R.string.TxtReplaceCallHint));
		dialog.setLeftKeyListener(new AlDialogOnClickListener() {

			@Override
			public void onClick() {
				// TODO Auto-generated method stub
				// 挂断电话
				ALVoipCallManager.getDefaultALVoipManager().handupCall();
				makeCall();
			}
		});
		dialog.showDialog();
	}

	private void showFavoriteErrorToast(int errorCode) {

		// 缺省为未知错误
		int txt = R.string.TxtUnknowError;
		switch (errorCode) {
		case XmppErrorCode.XMPP_ERROR_801:
			txt = R.string.TxtFavoriteError801;
			break;
		case XmppErrorCode.XMPP_ERROR_802:
			txt = R.string.TxtFavoriteError802;
			showInfoAlertDialog(getString(txt));
			return;
		case XmppErrorCode.XMPP_ERROR_803:
			txt = R.string.TxtFavoriteError803;
			break;

		default:
			break;
		}
		MyToastUtil.getInstance().showCenterToastOnCenter(txt);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#finish()
	 */
	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		// ALLocalEnv.getLocalEnv().clearImageLoaderMemoryCache();
		if (voiceIntroRecordTask != null) {
			voiceIntroRecordTask.setSaveCallback(null);
			voiceIntroRecordTask.setMediaUploadCallback(null);
			voiceIntroRecordTask = null;
		}
		// photo_pager.setOnPageChangeListener(null);
		stopViewPagerTask();
		releaseAudioLeaveMessageEnv();

	}

	/**************************************** 用户资料显示 ***************************************************/
	/**
	 * 设定图片显示布局为屏幕高度的2/3
	 */
	private void setupLayoutParam() {
		int height = ALDisplayMetricsManager
				.getScreenHeight(getApplicationContext()) / 3 * 2/**
		 * (int)
		 * ALDisplayMetricsManager .getScreenDensity(getApplicationContext())
		 */
		;
		RelativeLayout.LayoutParams parm = new RelativeLayout.LayoutParams(
				android.widget.RelativeLayout.LayoutParams.FILL_PARENT, height);
		layout_top.setLayoutParams(parm);
		flipper.setLayoutParams(parm);
		if (!isMyHomePage) {
			parm = new RelativeLayout.LayoutParams(
					RelativeLayout.LayoutParams.FILL_PARENT,
					RelativeLayout.LayoutParams.FILL_PARENT);
			parm.bottomMargin = (int) ALDisplayMetricsManager
					.getScreenDensity(getApplicationContext()) * 60;
			findViewById(R.id.main_layout).setLayoutParams(parm);
		}

	}

	/**
	 * 
	 */
	private void setupUserInfo() {

		// 设置昵称
		showTextMessage(R.id.user_center_msg, user.getNick());
		showTextMessage(R.id.nick, user.getNick());
		// 年龄地区
		showTextMessage(R.id.age_location,
				user.getAge() + " " + user.getLocation());
		// 设置魅力值
		showTextMessage(R.id.glamour_count, user.getGlamour());
		// 設定粉絲數
		showTextMessage(R.id.fans_count, user.getCollectingnum());
		// 設定簽名
		showTextMessage(R.id.sig, user.getSignature());

		// 顯示性別之類
		UserIconsUtil.setupIconsLayout(img_layout, user);

//		setupBottomPhotos();
		// 照片數
		showTextMessage(R.id.photo_count, user.getPhotos().size() + "");

		// 顯示頭像

		String imgFileId = user.getImageFileId();
		if (!TextUtils.isEmpty(user.getThumbAvatar())) {
			imgFileId = user.getThumbAvatar();
		}
		ALLocalEnv.getLocalEnv().displayImagePluginServerlet(imgFileId,
				user_icon,
				ALLocalEnv.getLocalEnv().getCycleImageDisplayOptions());

		if (!isMyHomePage) {
			if (TextUtils.isEmpty(user.getSignature())) {
				// 隱藏簽名欄
				goneView(R.id.edit_nick_layout);
			}
			if (isDataReceived) {
				showView(R.id.fun_layout);
				updateFunFavoriteState();
				updateFunCallState();
			} else {
				goneView(R.id.fun_layout);
			}
		} else {
			// 查看自己的界面
			if (isDataReceived) {
				if (user.getPhotos() == null || user.getPhotos().size() == 0) {
					// 没有头像,显示上传按钮
					showView(R.id.upload_pic_btn);
					setViewOnclickListener(R.id.layout_top, this);
				} else {
					// 有头像，隐藏上传按钮
					goneView(R.id.upload_pic_btn);
					setViewOnclickListener(R.id.layout_top, null);
				}
			}
		}

	}

	/**
	 * 设置查看他人资料时底部按钮状态
	 */
	private void updateFunFavoriteState() {
		if (isMyHomePage)
			return;
		if (user.isFavorite()) {
			showTextMessage(R.id.favorites, R.string.TxtFavorited);
			ViewUtils.setBackgroundRes(favorites_icon,
					R.drawable.personal_other_icon_attention02);
			// 已关注，更改按键名为解除关注
		} else {
			// 未關注
			showTextMessage(R.id.favorites, R.string.TxtFriends);
			ViewUtils.setBackgroundRes(favorites_icon,
					R.drawable.personal_other_icon_attention01);
		}
	}

	/**
	 * 设置查看他人资料时底部电话按钮的状态
	 */
	private void updateFunCallState() {

		if (isMyHomePage)
			return;
		boolean isUserBlockCall = user.isBlockstrangercall();
		boolean isUserBlockMsg = user.isBlockstrangermsg();
		boolean isFavorited = user.isFavorite();
		boolean isOnline = user.isOnline();
		boolean isCalling = user.isCalling();
		boolean isCallNotice = user.getCallNoticeState();

		String msg = "";
		msg = getString(R.string.TxtCallPrice);
		msg = String.format(msg, user.getCallPrice());
		showTextMessage(R.id.price, msg);
		msg = "";
		ViewUtils.setBackgroundRes(call_icon,
				R.drawable.personal_other_icon_call);
		// 缺省禁止语音留言
		disableAudioMsgRecorder();
		// 恢复拨号状态
		makeCallState = MAKE_CALL_REQUEST;

		call_layout.setEnabled(true);

		if (!isOnline) {
			// 离线
			msg = getString(R.string.TxtUserOffline);
			String pluginMsg = "";
			if (isUserBlockMsg && !isFavorited) {
				// 用户拒绝陌生人留言
				call_layout.setEnabled(false);
				ViewUtils.setBackgroundRes(call_icon,
						R.drawable.personal_other_icon_call_failure);
			} else {
				pluginMsg = getString(R.string.TxtLeaveAudioMsg);
				showTextMessage(R.id.price, "");
				makeCallState = LEAVE_AUDIO_MSG_REQUEST;
				// 准备语音留言
				enableAudioMsgRecorder();

			}
			msg = String.format(msg, pluginMsg);
			showTextMessage(R.id.call, msg);
		} else {

			if (isCalling) {
				// 通话中
				msg = getString(R.string.TxtUserCalling);
				String pluginMsg = "";
				if (isUserBlockMsg && !isFavorited) {
					// 用户屏蔽了陌生人留言
					call_layout.setEnabled(false);
					ViewUtils.setBackgroundRes(call_icon,
							R.drawable.personal_other_icon_call_failure);

				} else {
					pluginMsg = getString(R.string.TxtLeaveAudioMsg);
					makeCallState = LEAVE_AUDIO_MSG_REQUEST;
					// 准备语音留言
					enableAudioMsgRecorder();

				}
				msg = String.format(msg, pluginMsg);
				showTextMessage(R.id.call, msg);
			} else {

				if (isUserBlockCall && !isFavorited) {
					// 电话功能已关闭，且非关注用户。
					if (!isUserBlockMsg) {
						// 如果没有屏蔽陌生留言，那么可以按住留言
						if (!isUserBlockMsg) {
							// 这里要该文案
							msg = getString(R.string.TxtUserBlockCall);

							String pluginMsg = "";

							pluginMsg = getString(R.string.TxtLeaveAudioMsg);
							makeCallState = LEAVE_AUDIO_MSG_REQUEST;
							// 准备语音留言
							enableAudioMsgRecorder();
							msg += pluginMsg;
							showTextMessage(R.id.call, msg);
							showTextMessage(R.id.price, "");
						}
					} else {
						// 对方在线，但是阻止了陌生人电话，禁止电话按钮点击
						call_layout.setEnabled(false);
						ViewUtils.setBackgroundRes(call_icon,
								R.drawable.personal_other_icon_call_failure);
						showTextMessage(R.id.call, R.string.TxtUserBlockCall);
						showTextMessage(R.id.price, "");
					}
				} else {
					if (isCallNotice) {
						// makeCallState = CALL_NOTICE_REQUEST;
					}
					showTextMessage(R.id.call, R.string.TxtCall);
				}
			}

		}

	}

	/**
	 * 初始化用户大图轮播控件
	 */
	private void initViewFlipper() {
		flipper.removeAllViews();
		if (user.getPhotos().size() > 0) {
			for (int i = 0; i < user.getPhotos().size(); i++) {
				ALPhoto photo = user.getPhotos().get(i);
				ImageView iv = new ImageView(ALLocalEnv.getLocalEnv());
				// iv.setBackgroundResource(R.drawable.personal_default_bg);
				iv.setScaleType(ScaleType.CENTER_CROP);
				flipper.addView(iv, new LayoutParams(LayoutParams.FILL_PARENT,
						LayoutParams.FILL_PARENT));

				if (!TextUtils.isEmpty(photo.getPicPath())
						&& ALFileManager.isFileExsit(photo.getPicPath())) {

					Uri uri = Uri.fromFile(new File(photo.getPicPath()));
					ALLocalEnv
							.getLocalEnv()
							.getImageLoader()
							.displayImage(
									uri.toString(),
									iv,
									ALLocalEnv.getLocalEnv()
											.getLargeIconImageDisplayOption());
				} else {
					ALLocalEnv.getLocalEnv().displayImagePluginServerlet(
							photo.getPicFileid(),
							iv,
							ALLocalEnv.getLocalEnv()
									.getLargeIconImageDisplayOption());
				}
			}
			flipper.setInAnimation(this, android.R.anim.fade_in);
			flipper.setOutAnimation(this, android.R.anim.fade_out);
			// flipper.startFlipping();
		}
	}

	/**
	 * 初始化图片滚动显示部件
	 */
	private void initPhotoScrollViewPager() {
		photos = user.getPhotos();
		// adapter = new ImagePagerAdapter(getSupportFragmentManager(),
		// photos.size());
		// photo_pager.setAdapter(adapter);
	}

	/**
	 * 创建底栏
	 */
	private void setupBottomPhotos() {
		photos_layout.removeAllViews();

		int width = ALDisplayMetricsManager
				.getScreenWidth(getApplicationContext())
				/ SMALL_PHOTO_COUNT
				- 14
				* (int) ALDisplayMetricsManager
						.getScreenDensity(getApplicationContext());

		int margin = 5 * ((int) ALDisplayMetricsManager
				.getScreenDensity(getApplicationContext()));

		for (int i = 0; i < SMALL_PHOTO_COUNT; i++) {
			if (i < photos.size()) {

				ImageView item = new ImageView(this);

				LinearLayout.LayoutParams parm = new LinearLayout.LayoutParams(
						width, width);
				item.setPadding(margin, margin, margin, margin);
				// margin = 0;

				// parm.bottomMargin = margin;
				// parm.topMargin = margin;
				// parm.leftMargin = margin;
				// parm.rightMargin = margin;
				item.setScaleType(ScaleType.CENTER_CROP);
				item.setLayoutParams(parm);
				item.setTag(i);
				item.setOnClickListener(photoClickListener);
				photos_layout.addView(item, parm);

				ALLocalEnv.getLocalEnv().displayImagePluginServerlet(
						photos.get(i).getThumbnailFileid(), item,
						ALLocalEnv.getLocalEnv().getRoundImageDisplayOption());
				ALLog.d(("加入" + i + " fileid " + photos.get(i)
						.getThumbnailFileid()));
			} else {
				break;
			}

		}
	}

	private OnClickListener photoClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			int i = (Integer) v.getTag();
			gotoLargerPhotoActivity(i);
		}
	};

	/************************************************ 大头像显示 **************************************************/

	private final int CHANGE_PIC_PERIOD = 1500;

	private void invokePlayViewPage() {
		if (isPlayingPic) {
			stopViewPagerTask();
		} else {
			startViewPagerTask();
		}
		isUserCancelPlayPic = !isUserCancelPlayPic;

	}

	private void startViewPagerTask() {
		if (!isDataReceived)
			return;
		if (isUserCancelPlayPic)
			return;

		if (flipper.getChildCount() < 2)
			return;

		isPlayingPic = true;
		flipper.startFlipping();
		// mhandler.postDelayed(viewPagerTask, CHANGE_PIC_PERIOD);
		ViewUtils.setBackgroundRes(findViewById(R.id.play_pic),
				R.drawable.personal_picture_botton_stop);
	}

	private void stopViewPagerTask() {
		if (!isDataReceived)
			return;
		isPlayingPic = false;
		// mhandler.removeCallbacks(viewPagerTask);
		flipper.stopFlipping();
		ViewUtils.setBackgroundRes(findViewById(R.id.play_pic),
				R.drawable.personal_picture_botton_play);
	}

	private Runnable viewPagerTask = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			if (photos.size() == 1)
				return;
			curViewPagerIndex++;
			if (curViewPagerIndex == photos.size()) {
				curViewPagerIndex = 0;
			}
			mhandler.postDelayed(this, CHANGE_PIC_PERIOD);
		}
	};

	private Runnable displayIconTask = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			// adapter = new
			initPhotoScrollViewPager();
			initViewFlipper();
			setupUserInfo();
		}
	};

	/**
	 * 用于查看图片轮播
	 * 
	 * @author alonso lee
	 * 
	 */
	private class ImagePagerAdapter extends FragmentStatePagerAdapter {
		private final int mSize;

		public ImagePagerAdapter(FragmentManager fm, int size) {
			super(fm);
			mSize = size;
		}

		@Override
		public int getCount() {
			return mSize;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			// TODO Auto-generated method stub
			super.destroyItem(container, position, object);
			ALLog.d("销毁图片");

		}

		@Override
		public Fragment getItem(int position) {

			String fileId = photos.get(position).getPicFileid();
			return ImageDetailFragment.newInstance(fileId);
		}
	}

	/******************************** 打电话 **************************************/

	public void onALEvent(ALVoipEvent event) {
		if (!isActivityOn()) {
			return;
		}
		switch (event.getEventType()) {
		case ALVOIP_EVENT_POST_DATA_TO_RTP_SERVER_SUCCESS:
			// ALModuleManager.getDefaultModuleManager().postEventToModuleManager(
			// ALUiXmppRequestCreator.creatorALUiXmppEvent(
			// ALUiXmppRequestType.XMPP_MAKE_CALL_REQUEST,
			// user.getJid()));
			//
			ALUiXmppRequestCreator.postALUiXmppMakeCall(user.getJid(),
					ALUiXmppRequestCreator.MAKE_NORMAL_CALL);

			break;
		case ALVOIP_EVENT_POST_DATA_TO_RTP_SERVER_FAIL:
			break;
		case ALVOIP_EVENT_START_STREAM_TO_REMOTE_USER:
			break;
		case ALVOIP_EVENT_STOP_STREAM_TO_REMOTE_USER:
			break;
		default:
			break;
		}
	}

	/******************************************* 按键处理 *********************************************/
	/**
	 * 处理更改签名
	 */
	private void invokeEditSig() {
		if (!isMyHomePage)
			return;
		Intent i = new Intent(this, InputActivity.class);
		i.putExtra("type", InputActivity.INPUT_TYPE_SIG);
		startActivity(i);
	}

	/**
	 * 查看详细资料
	 */
	private void invokeViewUserDetail() {
		Intent i = new Intent(this, UserInfoDetailAcitivity.class);
		i.putExtra("user", user);
		startActivity(i);
	}

	/**
	 * 处理收藏取消收藏
	 */
	private synchronized void invokeFavoriteBtnClick() {
		if (ALLocalEnv.isSendXmppDataEnable()) {
			if (user.isFavorite()) {
				// 已經收藏，現在要取消收藏
				ALUiXmppRequestCreator.postALUiXmppDeleteFriendOrFans(
						ALUiXmppRequestCreator.REQUEST_DELETE_USER_FAVORITES,
						user.getJid());

			} else {
				// 还没有收藏，开始添加收藏
				ALUiXmppRequestCreator.postALUiXmppFavoritesFun(
						ALUiXmppRequestCreator.REQUEST_ADD_USER_FAVORITES,
						user.getJid());
			}
			isUserPlayFavoritesAction = true;
		}
	}

	/**
	 * 处理上传图片按钮
	 */
	private synchronized void invokeUploadPicBtnClick() {
		showPhotoProcessDialog();
	}

	/**
	 * 处理右上角
	 */
	private void invokeOptBtnClick() {
		if (isMyHomePage) {
			showShareDialog();
		} else {
			showOptDialog();
		}
	}

	/************************************** 上传头像 *********************************************/
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.TitleBarActivity#onGetProcessPhotosResult(java.lang
	 * .String, java.lang.String)
	 */
	@Override
	protected void onGetProcessPhotosResult(String path, String name) {
		// TODO Auto-generated method stub
		super.onGetProcessPhotosResult(path, name);
		Uri uri = Uri.fromFile(new File(path));
		ALLog.d("得到图片路径" + uri.toString());
		if (ALLocalEnv.isSendXmppDataEnable()) {
			// 上传图片
			uploadPic(path);
			showLoadingProgress();
		}
	}

	private ALPhoto tempPhoto;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.TitleBarActivity#handleUploadPicSuccess(com.alstudio
	 * .utils.android.net.http.UploadPhotoRequest, java.lang.String,
	 * java.lang.String)
	 */
	@Override
	protected void handleUploadPicSuccess(UploadPhotoRequest sender,
			String pictureFileId, String thumbFileId) {
		// TODO Auto-generated method stub
		super.handleUploadPicSuccess(sender, pictureFileId, thumbFileId);
		dismissLoadingProgress();
		if (!isMyHomePage)
			return;
		ALLog.d("图片上传成功 " + pictureFileId + "小兔 " + thumbFileId);
		tempPhoto = new ALPhoto();
		tempPhoto.setPicFileid(pictureFileId);
		tempPhoto.setThumbnailFileid(thumbFileId);
		tempPhoto.setPicPath(sender.getFilepath());
		tempPhoto.setThumbnailPath(sender.getFilepath());
		ALLocalEnv.getLocalEnv().getMyProfile().getPhotos().add(tempPhoto);
		ALLocalEnv
				.getLocalEnv()
				.getMyProfile()
				.setPhotoCount(
						ALLocalEnv.getLocalEnv().getMyProfile().getPhotos()
								.size());

		// 显示图片
		// photos.add(tempPhoto);
		mhandler.post(displayIconTask);
		// 保存用户资料
		User u = new User();
		// u.setPhotos(photos);
		u.getPhotos().add(tempPhoto);
		ALUiXmppRequestCreator.postALUiXmppModifyUserProfileEvent(u);

	}

	/**
	 * 查看那他人主页，弹出右上角对话框
	 */
	private void showOptDialog() {
		String blackListOpt = getString(R.string.TxtAddToBlackList);
		if (user.isInblacklist()) {
			blackListOpt = getString(R.string.TxtRemoveFromBlackList);
		}
		String fansOpt = getString(R.string.TxtRemoveFans);
		if (!user.isFans()) {
			fansOpt = null;
		}

		String[] items = null;

		items = new String[] { getString(R.string.TxtChargeUser), blackListOpt,
				fansOpt };

		final AlertDialogCreator mDialogCreator = AlertDialogCreator
				.createOneButtonWithListItemDialog(this, false, items);
		mDialogCreator.setItemClickListener(new AlItemOnClickListener() {

			@Override
			public void OnClick(int position) {
				// TODO Auto-generated method stub
				invokeOptItemClick(position);
			}
		});
		mDialogCreator.showDialog();

	}

	private void invokeOptItemClick(int position) {
		switch (position) {
		case 0:
			// 举报
			Intent i = new Intent(this, ChargeUserActivity.class);
			i.putExtra("jid", user.getJid());
			startActivity(i);
			break;
		case 1:
			// 黑名单
			showInvokeBlaickListDialog();
			break;
		}
	}

	private void showInvokeBlaickListDialog() {
		if (!user.isInblacklist()) {
			AlertDialogCreator dialog = AlertDialogCreator
					.createTwoButtonNormalDialog(this, false);
			dialog.setMessage(getString(R.string.TxtAddBlackListHint));
			dialog.setLeftKeyListener(new AlDialogOnClickListener() {

				@Override
				public void onClick() {
					// TODO Auto-generated method stub
					invokeBlackListOpt();
				}
			});
			dialog.showDialog();
			return;
		}
		invokeBlackListOpt();
	}

	/**
	 * 处理黑名单
	 */
	private void invokeBlackListOpt() {
		if (!ALLocalEnv.isSendXmppDataEnable())
			return;
		if (user.isInblacklist()) {
			ALLog.d("将" + user.getNick() + "移出黑名单");
			ALLocalEnv.getLocalEnv().getDatabase()
					.deleteUserFromBlackList(user.getJid());
			user.setInblacklist(false);
		} else {
			ALLog.d("将" + user.getNick() + "加入黑名单");
			ALLocalEnv.getLocalEnv().getDatabase().insertUserToBlackList(user);
			user.setInblacklist(true);
			if (user.isFavorite()) {
				// 已經收藏，現在要取消收藏
				ALUiXmppRequestCreator.postALUiXmppDeleteFriendOrFans(
						ALUiXmppRequestCreator.REQUEST_DELETE_USER_FAVORITES,
						user.getJid());
			}

			if (user.isFans()) {
				// 移除粉絲
				ALUiXmppRequestCreator.postALUiXmppDeleteFriendOrFans(
						ALUiXmppRequestCreator.REQUEST_DELET_USER_FANS,
						user.getJid());
			}

		}

		new Thread() {
			public void run() {
				ArrayList<User> users = ALLocalEnv.getLocalEnv().getDatabase()
						.getBlackListUsers();
				ALUiXmppRequestCreator.postALUiXmppBlackListFun(
						ALUiXmppRequestCreator.REQUEST_ADD_USER_TO_BLACKLIST,
						users);
			};
		}.start();
	}

	/************************************** 分享處理 ****************************************/

	public static final int SHARE_TO_SINA = 2;
	public static final int SHARE_TO_TENCENT = 3;

	public static final int SHARE_TO_WEIXIN = 4;
	public static final int SHARE_TO_WEIXIN_FRIEND = 5;

	private int shareType = SHARE_TO_SINA;

	private AlertDialogCreator mDialogCreator;

	private void showShareDialog() {

		View shareView = ALLocalEnv.getLocalEnv().getGlobalLayoutInflater()
				.inflate(R.layout.share_dialog_view, null);

		shareView.findViewById(R.id.weixin).setOnClickListener(this);
		shareView.findViewById(R.id.weixin_friend).setOnClickListener(this);
		shareView.findViewById(R.id.weibo).setOnClickListener(this);
		shareView.findViewById(R.id.qzone).setOnClickListener(this);

		mDialogCreator = AlertDialogCreator
				.createOneButtonWithCustomViewDialog(this, false, shareView);
		mDialogCreator.showDialog();
	}

	private void doItemSelect(int which) {
		saveShareMagicPic();
	}

	private void doShareNomal() {
		ArrayList<WeiboShareMenuItem> menus = WeiboShareUtil
				.getDefaultShareMenuItem(this);

		ShareContentParam param = new ShareContentParam();
		param.mShareType = ShareContentParam.SHARE_TYPE_HOME_PAGE;
		param.isShareUrl = false;
		param.bareJid = ALLocalEnv.getBareJid(user.getJid());
		// 分享文案
		param.shareContent = WeiboShareUtil.getShareTextWithParam(shareType,
				param, getApplicationContext());

		if (shareType == WeiboShareUtil.SHARE_TO_WEIXIN_2
				|| shareType == WeiboShareUtil.SHARE_TO_WEIXIN_FRIEND) {
			if (!WeiXinShareDialog.isWeixinInstall()) {
				WeiXinShareDialog.showInstallWeixin(this);
				return;
			}
		}

		shareDirect(shareType, param, false, false, "10010",
				ALSdcardManager.getExtStoragePath() + "/WeiboShareImage.png");

	}

	private boolean isSaving = false;

	private synchronized void saveShareMagicPic() {
		if (isSaving) {
			return;
		}
		mDialogCreator.dismissDialog();

		isSaving = true;
		setLoadingProgressCancelAble(false);
		showLoadingProgress();
		saveMyHomePage();
	}

	private final int SAVE_SUCCESS = 1;
	private final int SAVE_ERROR = 2;
	private Handler mShareHandler = new Handler() {
		public void handleMessage(Message msg) {
			isSaving = false;
			dismissLoadingProgress();
			switch (msg.what) {
			case SAVE_SUCCESS:
				doShareNomal();
				break;
			case SAVE_ERROR:
				MyToastUtil.getInstance().showToastOnCenter(
						getString(R.string.TxtSaveFail));
				break;
			}
		};
	};

	private void saveMyHomePage() {
		new Handler().post(new Runnable() {

			@Override
			public void run() {
				final ScreenCaptureUtil util1 = new ScreenCaptureUtil();

				final Bitmap main_layout = util1.prepare(
						UserHomePageAcitivty.this, R.id.main_layout);

				WeiboShareUtil.saveBitmap(ALSdcardManager.getExtStoragePath()
						+ "/WeiboShareImage.png", main_layout,
						new SaveImageCallback() {

							@Override
							public void onSaveSuccess(String path) {
								// TODO Auto-generated method stub
								// 保存成功
								util1.recycleBitmap();
								main_layout.recycle();
								mShareHandler.sendEmptyMessage(SAVE_SUCCESS);
							}

							@Override
							public void onSaveFail() {
								// TODO Auto-generated method stub
								// 保存失败
								util1.recycleBitmap();
								main_layout.recycle();
								mShareHandler.sendEmptyMessage(SAVE_ERROR);
							}
						});
			}
		});

	}

	/********************************* 语音介绍 ***************************************/

	/**
	 * 初始化语音签名播放器
	 */
	private void initAudioPlayer() {
		mAudioPlayTask = new ALAudioPlayTask(getApplicationContext(), "",
				VersionConfig.AUDIO_PATH, this);
	}

	private void setAudioPlayerFileid() {
		mAudioPlayTask.setFildId(FileIdUtils.getBareFileId(user.getVoiceintro()
				.getVoiceFileUrl()));
		if (isMyHomePage) {
			if (!TextUtils.isEmpty(user.getVoiceintro().getVoiceFileUrl())) {
				setViewBackground(R.id.mute,
						R.drawable.personal_picture_botton_sound_off);
				// goneView(R.id.record_btn);
			}
		}
	}

	private void invokePlayAudioSig() {
		if (mAudioPlayTask.isPlaying()) {
			stopPlayVoiceSig();
		} else {
			playVoiceSig();
		}
	}

	/**
	 * 播放语音签名
	 */
	private void playVoiceSig() {
		if (TextUtils.isEmpty(mAudioPlayTask.getFildId()))
			return;
		mAudioPlayTask.setAudioUrl(ALLocalEnv.getLocalEnv()
				.createAudioDownloadUrl(mAudioPlayTask.getFildId()));
		mAudioPlayTask.Play();
	}

	private void stopPlayVoiceSig() {
		mAudioPlayTask.stop();
	}

	private void showVoiceSig(User u) {

		final Voiceintro voiceintro = u.getVoiceintro();

		if (ALAudioRecordManager.isLocalAudioExsit()
				|| !TextUtils.isEmpty(voiceintro.getVoiceFileUrl())) {
			boolean isFileid = true;
			String audioPath = voiceintro.getVoiceFileUrl();
			int second = 0;
			if (ALAudioRecordManager.isLocalAudioExsit()) {
				isFileid = false;
				audioPath = ALAudioRecordManager.loadAudioPath();
				ALLog.d("本地语音地址" + audioPath);
				second = ALAudioRecordManager.getAudioLen();
				mAudioPlayTask.setAudioPath(audioPath);
			} else {
				audioPath = voiceintro.getVoiceFileUrl();
				second = voiceintro.getAudioLen();
				mAudioPlayTask.setFildId(FileIdUtils.getBareFileId(audioPath));

			}
			// initAudioPlayTask(audioPath, isFileid);

		} else {
			// 无语音签名，隐藏播放按钮
			// hideView(R.id.play);
			// 隐藏重录按钮
			// hideView(R.id.recall);
			// 隐藏进度条
			// hideView(R.id.play_voice_recorder_pbar);
			// 隐藏录音时间
			// hideView(R.id.record_time);
			// 显示录制按钮
			// showView(R.id.reord);
			// 重置进度
			// play_voice_recorder_pbar.setProgress(0);
			// 灰色的录音图标
			// setBackgroundRes(R.id.record_state,
			// R.drawable.data_icon_mic_off);
			// setViewOnclickListener(R.id.reord, recordClickListener);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.net.http.http2.UploadMediaRequest.
	 * MediaUploadCallback
	 * #onSuccess(com.alstudio.utils.android.net.http.http2.UploadMediaRequest,
	 * java.lang.String)
	 */
	@Override
	public void onSuccess(UploadMediaRequest sender, String fileId) {
		// TODO Auto-generated method stub
		if (isMyHomePage) {
			// 只有查看自己资料才能上传语音介绍
			ALUiXmppRequestCreator.postALUiXmppCommitVoiceIntroEvent(fileId,
					this.audioLen + "");
			dismissLoadingProgress();
		} else {
			if (!isRecordingAudioMessage) {
				ALLog.d("谁在上传语音留言");
				return;
			}
			ALLog.d("语音留言上传成功,开始发送数据");
			ALUiXmppRequestCreator.postALUiXmppSendAudioLeaveMessage(user,
					fileId);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.net.http.http2.UploadMediaRequest.
	 * MediaUploadCallback
	 * #onFailed(com.alstudio.utils.android.net.http.http2.UploadMediaRequest,
	 * int)
	 */
	@Override
	public void onFailed(UploadMediaRequest sender, int errCode) {
		// TODO Auto-generated method stub
		if (isMyHomePage) {
			dismissLoadingProgress();
		} else {
			ALLog.d("语音留言上传失败");
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.net.http.http2.UploadMediaRequest.
	 * MediaUploadCallback
	 * #onCancelled(com.alstudio.utils.android.net.http.http2.
	 * UploadMediaRequest)
	 */
	@Override
	public void onCancelled(UploadMediaRequest sender) {
		// TODO Auto-generated method stub
		dismissLoadingProgress();

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.net.http.http2.UploadMediaRequest.
	 * MediaUploadCallback
	 * #onProcessing(com.alstudio.utils.android.net.http.http2
	 * .UploadMediaRequest, long, long)
	 */
	@Override
	public void onProcessing(UploadMediaRequest sender, long processedSize,
			long totalSize) {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.media.audio.recorder.ALAudioRecordTask.
	 * ALAudioRecordTaskCallback#onAudioSaved(java.lang.String, int)
	 */
	@Override
	public void onAudioSaved(String path, int audioLen) {
		// TODO Auto-generated method stub
		showLoadingProgress();
		showVoiceSig(ALLocalEnv.getLocalEnv().getMyProfile());
		this.audioLen = audioLen;
		// 開始上傳
		String servletUrl = Serverlet
				.getUploadServerUrl(Serverlet.UPLOAD_AUDIO_SERVERLET);

		ALHttpUploadTaskManager.UploadVoiceIntroRequest(servletUrl, path, this);
		ALLog.d("请求上传语音介绍 ");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.media.audio.recorder.ALAudioRecordTask.
	 * ALAudioRecordTaskCallback#onWindowShowed()
	 */
	@Override
	public void onWindowShowed() {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.media.audio.recorder.ALAudioRecordTask.
	 * ALAudioRecordTaskCallback#onWindowDismissed()
	 */
	@Override
	public void onWindowDismissed() {
		// TODO Auto-generated method stub

	}

	/**************************************** 发送语音留言 **********************************************/

	private final int UPDATE_AUDIO_MSG_STATE_TIMEOUT = 1000;

	private UploadMediaRequest uploadAudioReq;

	private boolean isRecordingAudioMessage = false;;

	private void releaseAudioLeaveMessageEnv() {
		if (isMyHomePage) {
			return;
		}

		// 移除语音留言
		if (audioRecorder != null) {
			mhandler.removeCallbacks(updateAudioMsgState);
			audioRecorder.setSaveCallback(null);
			audioRecorder = null;
		}

		if (uploadAudioReq != null) {
			uploadAudioReq.cancel();
			uploadAudioReq = null;
		}
	}

	// 语音留言录音回调
	private ALAudioRecordTaskCallback audioMsgRecorderCallback = new ALAudioRecordTaskCallback() {

		@Override
		public void onWindowShowed() {
			// TODO Auto-generated method stub

		}

		@Override
		public void onWindowDismissed() {
			// TODO Auto-generated method stub

		}

		@Override
		public void onAudioSaved(String path, int audioLen) {
			// TODO Auto-generated method stub
			ALLog.d("语音留言保存成功 " + path + " 语音长度 " + audioLen);
			if (!ALLocalEnv.isSendXmppDataEnable())
				return;
			disableAudioMsgRecorder();
			disableCallLayout();
			showTextMessage(R.id.call, R.string.TxtLeaveMessageSending);
			showTextMessage(R.id.price, "");
			ViewUtils.setBackgroundRes(call_icon, 0);
			isRecordingAudioMessage = true;
			// 開始上傳
			String servletUrl = Serverlet
					.getUploadServerUrl(Serverlet.UPLOAD_AUDIO_SERVERLET);

			uploadAudioReq = ALHttpUploadTaskManager.UploadVoiceIntroRequest(
					servletUrl, path, UserHomePageAcitivty.this);
			ALLog.d("请求上传语音留言 ");

		}
	};

	/**
	 * 初始化语音留言录音器
	 */
	private void initAudioMsgRecorder() {
		audioRecorder = new ALAudioRecordTask2(getApplicationContext(),
				VersionConfig.AUDIO_PATH, findViewById(R.id.main_layout),
				call_layout);
		audioRecorder.disableView4Ptt();
		audioRecorder.setSaveCallback(audioMsgRecorderCallback);
	}

	/**
	 * 开启语音留言
	 */
	private void enableAudioMsgRecorder() {
		disableCallLayout();
		// 初始化语音留言
		audioRecorder.resetView4Ptt();
	}

	/**
	 * 禁止语音留言
	 */
	private void disableAudioMsgRecorder() {
		enableCallLayout();
		// 初始化语音留言
		audioRecorder.disableView4Ptt();
	}

	private void disableCallLayout() {
		call_layout.setOnClickListener(null);
	}

	private void enableCallLayout() {
		call_layout.setOnClickListener(this);
	}

	@Override
	public void handleOnMessageReceiptEvent() {
		// TODO Auto-generated method stub
		super.handleOnMessageReceiptEvent();
		showTextMessage(R.id.call, R.string.TxtLeaveMessageSended);
		mhandler.postDelayed(updateAudioMsgState,
				UPDATE_AUDIO_MSG_STATE_TIMEOUT);
	}

	private Runnable updateAudioMsgState = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			updateFunCallState();
		}
	};

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub
		stopViewPagerTask();
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub
		stopViewPagerTask();
	}

	@Override
	public void onPageSelected(int arg0) {
		// TODO Auto-generated method stub
		curViewPagerIndex = arg0;
		startViewPagerTask();
	}

	/*************************************** 播放语音签名回调 **********************************************/
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.media.audio.player.ALMusicPlayerCallback#
	 * onMusicPlay()
	 */
	@Override
	public void onMusicPlay() {
		// TODO Auto-generated method stub
		// 开始播放
		setViewBackground(R.id.mute,
				R.drawable.personal_picture_botton_sound_on);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.media.audio.player.ALMusicPlayerCallback#
	 * onMusicStop()
	 */
	@Override
	public void onMusicStop() {
		// TODO Auto-generated method stub
		setViewBackground(R.id.mute,
				R.drawable.personal_picture_botton_sound_off);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.media.audio.player.ALMusicPlayerCallback#
	 * onMusicPause()
	 */
	@Override
	public void onMusicPause() {
		// TODO Auto-generated method stub
		setViewBackground(R.id.mute,
				R.drawable.personal_picture_botton_sound_off);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.media.audio.player.ALMusicPlayerCallback#
	 * onMusicError()
	 */
	@Override
	public void onMusicError() {
		// TODO Auto-generated method stub
		setViewBackground(R.id.mute,
				R.drawable.personal_picture_botton_sound_off);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.media.audio.player.ALMusicPlayerCallback#
	 * onMusicProgressChanged(int)
	 */
	@Override
	public void onMusicProgressChanged(int second) {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.media.audio.player.ALAudioPlayTask.
	 * ALAudioPlayTaskCallback#onUpdateProcess(int)
	 */
	@Override
	public void onUpdateProcess(int percent) {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.media.audio.player.ALAudioPlayTask.
	 * ALAudioPlayTaskCallback#onDownloadFinish(java.lang.String)
	 */
	@Override
	public void onDownloadFinish(String path) {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.media.audio.player.ALAudioPlayTask.
	 * ALAudioPlayTaskCallback#onPreDownload()
	 */
	@Override
	public void onPreDownload() {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.media.audio.player.ALAudioPlayTask.
	 * ALAudioPlayTaskCallback
	 * #onDownloadFail(com.alstudio.utils.android.net.download
	 * .ALHttpDownloadTask.ALHttpDownloadErrorCode)
	 */
	@Override
	public void onDownloadFail(ALHttpDownloadErrorCode code) {
		// TODO Auto-generated method stub

	}
}
